// index.js
// 获取应用实例
var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
var qqmapsdk;
Page({
  data: {
    name: '',
    distance: '***',
    time: '',
    scale: "11",
    open: false,
    flag1: true,
    istoright: true,
    flat: "0",
    flag: '0',
    latitude: '21.109384',
    longitude: '110.490444',
    currentLatitude: '',
    currentLongitude: '',
    targetLatitude: '',
    targetLongitude: '',
    start_latitude: '',
    start_longitude: '',
    stop_latitude: '',
    stop_longitude: '',
    markers: [],
    points: [],
    rows: [],
    polyline: [{
      points: [],
      color: "#CCCC99",
      width: 10,
      arrowLine: true
    }],
    includePoints: [],
    rotate:'',
    degree:''
  },

  //标记已收
  mark_point: function (e) {
    // 页面data-id传进来的索引
    // const id = e.currentTarget.dataset.id;
    //根据id请求后端改数据
    var that = this

    wx.request({
      url: 'https://www.zhenfu.online/locate/update/' + e.currentTarget.dataset.id,
      method: 'PUT',
      success: (res) => {
        //重新查取海网列表数据
        wx.request({
          url: 'https://www.zhenfu.online/locate/list',
          method: 'GET',
          success: (res) => {
            // console.log(res);
            that.setData({
              rows: res.data.data
            })
          }
        })
      }
    })
  },

  // 回到自己定位点
  goBack: function clickcontrol(e) {
    let mpCtx = wx.createMapContext("map")
    mpCtx.moveToLocation()
  },
  // 操作海网(已完成)
  tap_ch: function (e) {
    if (this.data.open) {
      this.setData({
        open: false
      });
    } else {
      this.setData({
        open: true
      });
    }
  },

  // 删除海网(已完成)
  delete_sea_net: function (e) {
    var that = this
    var toast = null
    console.log("打印")
    console.log(e.currentTarget.dataset.id)
    // 根据id查询单个
    wx.request({
      url: 'https://www.zhenfu.online/locate/delete/' + e.currentTarget.dataset.id,
      method: 'GET',
      success: (res) => {
        console.log(res)
        toast = "确定删除  " + res.data.data.create_time + "--" + "第" + res.data.data.index_net + "排  吗？"
        console.log("打印toast")
        console.log(toast)
        wx.showModal({
          title: toast,
          success(res) {
            if (res.confirm) {
              // 用户点击确定，根据id发起请求删除position
              wx.request({
                url: 'https://www.zhenfu.online/locate/' + e.currentTarget.dataset.id,
                method: 'DELETE',
                success: (res) => {
                  console.log("===============================")
                  console.log(res)
                  wx.showToast({
                    title: res.data.data,
                    icon: 'success',
                    duration: 1500
                  })
                  // 刷新渔网数组数据
                  wx.request({
                    url: 'https://www.zhenfu.online/locate/list',
                    method: 'GET',
                    success: (res) => {
                      console.log(res);
                      that.setData({
                        rows: res.data.data
                      })
                    }
                  })
                }
              })
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    })




  },

  // startCompass:function(){  
  //   var that = this
  //   wx.startCompass({
  //     success: function(){  //启动传感器
  //       wx.onCompassChange(function(res){ 
  //         let degree = res.direction.toFixed(0);
  //         that.setData({    
  //           resCompass:res,
  //           rotate:360 - degree
  //         })
  //       })
  //     },
  //   })
  // },
  // stopCompass:function(){
  //   var that = this;
  //   wx.stopCompass({
  //     success: function(res){//停止传感器
  //       that.setData({    
  //         res : '',
  //         resCompass:res,
  //         rotate:0
  //       })
  //     },
  //   })
  // },
  // 根据id去查询对应的position(已完成)
  select_sea_net: function (e) {

    // 选择海网之后
    this.setData({
      markers: [],
      flat: '3',
      flag: '2',
      flag1: false
    })
    var that = this
    console.log("打印根据id查询position")
    console.log(e.currentTarget.dataset.id)

    function location(latitude, longitude) {
      this.latitude = latitude;
      this.longitude = longitude;
    }

    wx.request({
      url: 'https://www.zhenfu.online/locate/' + e.currentTarget.dataset.id,
      method: 'GET',
      success: (res) => {
        console.log("======get======")
        console.log(res.data.data)
        //通过实例化来创建对象
        var location1 = new location(res.data.data[0].latitude, res.data.data[0].longitude)
        var location2 = new location(res.data.data[1].latitude, res.data.data[1].longitude)
        that.setData({
          name: res.data.data[0].callout.content,
          targetLatitude: res.data.data[0].latitude,
          targetLongitude: res.data.data[0].longitude,
          // 设置polyline折线
          // 'polyline[0].points': res.data.data,
          // 为每个对象设置callout
          points: [location1, location2],
          markers: res.data.data,
        })
        console.log('查看一下定位信息')
        console.log(this.data.name)
        console.log(this.data.targetLatitude)
        console.log(this.data.targetLongitude)
        this.calculateDistanceFun()

      }
    })

    // 返回定位的主页
    if (this.istoright) {
      this.setData({
        open: true
      });
    } else {
      this.setData({
        open: false
      });
    }


  },


  calculateDistanceFun() {

    var that = this
    const _onLocationChange = function (res) {
      wx.onLocationChange((res) => {
        // console.log("看一下res是什么")
        console.log(res)
        that.setData({

          currentLatitude: res.latitude,
          currentLongitude: res.longitude
        })
        qqmapsdk.calculateDistance({
          mode: 'straight', //直线距离
          // 起点坐标
          from: {
            latitude: that.data.currentLatitude,
            longitude: that.data.currentLongitude,
          },
          // 终点坐标 to是当前位置 注意是一个数组
          to: [{
            // 选择的地址目标
            latitude: that.data.targetLatitude,
            longitude: that.data.targetLongitude,
          }],
          success: (calc) => {
            // 计算结果输出为米
            function location(latitude, longitude) {
              this.latitude = latitude;
              this.longitude = longitude;
            }
            var currLocation = new location(that.data.currentLatitude, that.data.currentLongitude)
            var targLocation = new location(that.data.targetLatitude, that.data.targetLongitude)
            let distance = calc.result.elements[0].distance;
            that.setData({
              'polyline[0].points': [currLocation, targLocation],
              includePoints: [currLocation, targLocation],
              distance: distance,
            })
            console.log(calc)
            console.log("计算距离为:", distance + '米');
            if(distance<100){
              wx.vibrateLong({
                // type: 'heavy',
                success: ()=>{
                  console.log("距离小于50米")
                }

              })
            }
          },
          // 失败的情况
          fail: (error) => {
            console.error('calculateDistance失败原因:', error);
          },
        })
      })
    }
    wx.startLocationUpdate({
      type: 'gcj02',
      success: (res) => {
        wx.onLocationChange(_onLocationChange)
      },
      fail: (error) => {
        console.log('startLocationUpdate失败原因:', error)
      }
    })
  },

  // 点击空白处返回(已完成)
  tap_end: function (e) {
    if (this.istoright) {
      this.setData({
        open: true
      });
    } else {
      this.setData({
        open: false
      });
    }
  },

  // 页面加载(已完成)
  onLoad: function () {

    var that = this
    setTimeout(() => {
      that.setData({
        show: false
      })
    }, 2000);

    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'MA2BZ-UI6KM-NJD62-6YX4C-O22M6-HQBD6'
    });

    wx.request({
      url: 'https://www.zhenfu.online/locate/list',
      method: 'GET',
      success: (res) => {
        console.log(res);
        that.setData({
          rows: res.data.data
        })
      }
    })
    wx.startCompass({
      success: function(){  //启动传感器
        wx.onCompassChange(function(res){ 
          console.log("罗盘")
          console.log(res)
          let degree = res.direction.toFixed(0);
          that.setData({    
            // resCompass:res,
            // rotate:360 - degree
            degree: degree
          })
          // console.log(res.data.rotate)
        })

      },
    })
  },

  // 开始定位(已完成)，小程序map组件坐标系是gcj02坐标系
  startPosition: function () {
    // 获取当前的经纬度
    var that = this
    wx.showModal({
      title: '确定开始定位吗？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          that.setData({
            time: 1 * 2 * 60 * 1000,
            flat: "1",
          })
          wx.getLocation({
            altitude: true,
            isHighAccuracy: true,
            highAccuracyExpireTime: 5000,
            type: 'gcj02',
            success(res) {
              that.data.start_latitude = res.latitude
              that.data.start_longitude = res.longitude
              console.log(res)
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

  finish: function () {
    console.log("finish事件执行")
    this.setData({
      time2: '',
    })
  },

  //结束导航
  stopNavigation: function () {
    // function location(latitude, longitude) {
    //   this.latitude = latitude;
    //   this.longitude = longitude;
    // }
    // var location5 = new location(21.374961,110.289984)
    // var location6 = new location(21.401203,110.370278)
    this.setData({
      'polyline[0].points': [],
      includePoints: [],
      markers: [],
      points:[],
      // includePoints:[location5,location6],
      flat: '0',
      flag: '3',
      flag1: true
    })
    wx.offLocationChange()

  },

  //停止定位(已完成)
  stopPosition: function () {
    // 获取当前的经纬度
    var that = this
    wx.getLocation({
      altitude: true,
      isHighAccuracy: true,
      highAccuracyExpireTime: 5000,
      type: 'gcj02',
      success(res) {
        that.data.stop_latitude = res.latitude
        that.data.stop_longitude = res.longitude
        console.log(res)
        // 请求服务器存储定位坐标
        wx.request({
          url: 'https://www.zhenfu.online/locate/save',
          method: 'POST',
          data: {
            start_latitude: that.data.start_latitude,
            start_longitude: that.data.start_longitude,
            stop_latitude: that.data.stop_latitude,
            stop_longitude: that.data.stop_longitude
          },
          success: (res) => {
            console.log(res);
            // 定位成功后，刷新渔网数组数据
            wx.request({
              url: 'https://www.zhenfu.online/locate/list',
              method: 'GET',
              success: (res) => {
                console.log(res);
                that.setData({
                  rows: res.data.data
                })
              }
            })
            wx.showToast({
              title: '保存成功！',
              icon: 'success',
              duration: 2000
            })
          }
        })
      }
    })
    this.setData({
      flat: "0",
    })

  },

  finish2: function () {
    console.log("finish2事件执行")
    //3分钟后自动结束定位
    this.stopPosition()
    this.setData({
      time3: ''
    })

  },
})